package com.banciyuan.bcywebview.biz.privatemessage;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.MessageApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.PrivateMessage;

/**
 * Created by squall on 2016/9/9.
 */
public class PrivateMessageFragment extends BaseLazyContainerFragment {

    private PullToRefreashRecycleView mRefreash;
    private RecyclerView recyclerView;
    private RequestQueue queue;

    private List<PrivateMessage> plist = new ArrayList<>();
    private PrivateMessageListAdapter talkListAdapter;
    private int type;
    private int page = 1;
    private boolean is_load;
    private boolean is_end;

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.refresh_recycle_layout, null);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        type = getArguments().getInt("type");
        queue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initUi(View rootview) {
        mRefreash = (PullToRefreashRecycleView) rootview.findViewById(R.id.listView);
        recyclerView = mRefreash.getRefreshableView();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        talkListAdapter = new PrivateMessageListAdapter(plist, getActivity(), type);
        recyclerView.setAdapter(talkListAdapter);
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initAction() {

        recyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!is_load && !is_end) {
                    page++;
                    initData();
                }
            }
        });

        mRefreash.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                is_load = false;
                is_end = false;
                page = 1;
                initData();
            }
        });
    }

    @Override
    protected void initData() {
        is_load = true;
        String url = HttpUtils.BASE_URL;
        if (type == 0) {
            url += MessageApi.getMessageInBox();
        } else {
            url += MessageApi.getMessageOutBox();
        }
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(response);
                        List<PrivateMessage> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<PrivateMessage>>() {
                        }.getType());
                        renderData(templist);
                    } else {
                        mProgressbarHelper.onFailed();
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);
    }

    private void renderData(List<PrivateMessage> templist) {
        if (page == 1) {
            plist.clear();
        }
        if (templist.isEmpty()) {
            is_end = true;
        }
        plist.addAll(templist);
        if (talkListAdapter == null) {
            talkListAdapter = new PrivateMessageListAdapter(plist, getActivity(), type);
            recyclerView.setAdapter(talkListAdapter);
        } else {
            talkListAdapter.notifyDataSetChanged();
        }
        mRefreash.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        is_load = false;
    }

    public boolean getAllClear() {
        for (PrivateMessage p : plist) {
            if (!p.is_read()) {
                return false;
            }
        }
        return true;
    }
}
